package com.laikan.reader.core.utils;

import android.text.TextUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.bean.BaseListDataBean;
import com.laikan.reader.core.bean.ChapterBean;
import com.laikan.reader.database.Book;
import com.laikan.reader.database.DBBook;
import com.socks.library.KLog;

import java.io.File;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class BookFileUtils {

    /**
     * 活动启动页图片缓存路径
     */
    public static final String SPLASHIMGFILEPATH = "/LaikanReader/data/cache";
    /**
     *
     */
    public static final String POSTERIMGFILEPATH = "/LaikanReader/data/cache/poster";

    /**
     * 书架列表缓存文件路径
     */
    public static final String BOOKLISTFILEPATH = "/LaikanReader/book/MyBook/booklist";

    /**
     * 二维码活动礼包信息缓存文件路径
     */
    public static final String FESTIVALINFOFILEPATH = "/LaikanReader/data/cache/FestivalArray";

    public static final String BOOKCONTENTPATH =  "/LaikanReader/book/";

    public static final String TAG = "BookSortUtil";

    /**
     * 根据bookid 删除 books 中的数据,然后保存
     *
     * @param bookids 多个bookid
     * @param books 书架现有的书籍
     */
    public static void delLocalBookByIds(ArrayList<String> bookids, List<Book> books) {
        // 删除多本书
        for (int i = 0; i < bookids.size(); i++) {
            String bookid = bookids.get(i);
            for (int j = 0; j < books.size(); j++) {
                if (bookid.equals(books.get(j).getId())) {
                    books.remove(j);
                    DBBook.getInstance().deleteByBookId(bookid);
                    // 初始化该书籍的读取记录
//                    SPUtil.putInt(bookid + "chaptep_rec", 0);
//                    SPUtil.putInt(bookid + "recCurPage", 0);
                }
            }
        }
    }

    public static void saveBooks() {
        BaseDataBean<BaseListDataBean<Book>> toJson = new BaseDataBean<>();
        toJson.setData(new BaseListDataBean<Book>());
        //        toJson.getData().setData(bookList);
        Gson gson = new Gson();
        String json2 = gson.toJson(toJson);
        saveFile(json2);
        //        sort = 0;
        //        bookList.clear();
    }

    /**
     * @param json 要保存的json字符串
     */
    private static void saveFile(String json) {
        File file = PublicUtil.getFile(BookFileUtils.BOOKLISTFILEPATH);
        if (!file.isDirectory()) {
            file.delete();
            file.mkdirs();
        }
        if (!file.exists()) {
            file.mkdirs();
        }
        FileUtil.writeFile(file.getPath(), json);
    }

    /**
     * 读取书架列表缓存数据
     */
    public static ArrayList<Book> readCacheBooklist() {

        if (!SPUtil.getBoolean("is_book_datas_in_db", false)) {
            File file = PublicUtil.getFile(BookFileUtils.BOOKLISTFILEPATH);
            BaseDataBean<BaseListDataBean<Book>> result;
            try {
                Gson gson = new Gson();
                Type type = new TypeToken<BaseDataBean<BaseListDataBean<Book>>>() {}.getType();
                String json = FileUtil.readFileString(file.getPath());
                if (json != null) {
                    KLog.json("readCacheBooklist::", json);
                    result = gson.fromJson(json, type);
                    ArrayList<Book> books = result.getData().getData();
                    for (int i = books.size()-1; i >= 0; i--) {
                        DBBook.getInstance().insertBook(books.get(i));
                    }
                }
                FileUtil.deleteFile(file);
                SPUtil.putBoolean("is_book_datas_in_db", true);
            }catch (Exception e) {
                KLog.e("readCacheBooklist() 解析书架json异常");
            }
        }
        return (ArrayList<Book>)DBBook.getInstance().queryAllBook();
    }

    /**
     * 保存书籍目录
     */
    public static void saveBookDirectory(String json, String bookid) {
        File file = PublicUtil.getRootPath();
        file = new File(file.getPath() + "/LaikanReader/book/" + bookid + "/chapter");
        if (!file.isDirectory()) {
            file.delete();
            file.mkdirs();
        }
        if (!file.exists()) {
            file.mkdirs();
        }
        FileUtil.writeFile(file.getPath(), json);
    }

    /**
     * 记录有效章节数到sp中
     *
     * @param chs
     *
     * @date 2015-11-24 上午9:48:20
     */
    public static void totalChapter(String bookid, ArrayList<ChapterBean> chs) {
        int chapterCount = 0;
        for (int i = 0; i < chs.size(); i++) {
            if (!chs.get(i).isVolume()) {
                chapterCount++;
            }
        }
        SPUtil.putInt("chap_count_" + bookid, chapterCount);
    }

    /**
     * 判断是否未登录
     *
     * @return true:未登录    false:已登录
     */
    public static boolean isNoLogin() {
        return TextUtils.isEmpty(SPUtil.getString("user_id", "")) || "0".equals(SPUtil.getString("user_id", ""));
    }

    // 获取文件
    //Context.getExternalFilesDir() --> SDCard/Android/data/你的应用的包名/files/ 目录，一般放一些长时间保存的数据
    //Context.getExternalCacheDir() --> SDCard/Android/data/你的应用包名/cache/目录，一般存放临时缓存数据
    public static long getFolderSize(File file) throws Exception {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            if(fileList == null) return 0;
            for (int i = 0; i < fileList.length; i++) {
                // 如果下面还有文件
                if (fileList[i].isDirectory()) {
                    size = size + getFolderSize(fileList[i]);
                } else {
                    size = size + fileList[i].length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    /**
     * 格式化单位
     *
     * @param size
     * @return
     */
    public static String getFormatSize(double size) {
        if (size <= 0) {
            return "0MB";
        }
        double megaByte = size / (1024 * 1024);
        BigDecimal result = new BigDecimal(Double.toString(megaByte));
        return result.setScale(2, BigDecimal.ROUND_HALF_UP)
                       .toPlainString() + "MB";
        //        double kiloByte = size / 1024;
        //        if (kiloByte < 1 && kiloByte > 0) {
        //            return "1KB";
        //        }else if(kiloByte == 0){
        //            return "0KB";
        //        }
        //
        //        double megaByte = kiloByte / 1024;
        //        if (megaByte < 1) {
        //            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
        //            return result1.setScale(0, BigDecimal.ROUND_HALF_UP)
        //                       .toPlainString() + "KB";
        //        }
        //        double gigaByte = megaByte / 1024;
        //        if (gigaByte < 1) {
        //            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
        //            return result2.setScale(1, BigDecimal.ROUND_HALF_UP)
        //                       .toPlainString() + "MB";
        //        }
        //        double teraBytes = gigaByte / 1024;
        //        if (teraBytes < 1) {
        //            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
        //            return result3.setScale(1, BigDecimal.ROUND_HALF_UP)
        //                       .toPlainString() + "GB";
        //        }
        //        BigDecimal result4 = new BigDecimal(teraBytes);
        //        return result4.setScale(1, BigDecimal.ROUND_HALF_UP).toPlainString()
        //               + "TB";
    }


    public static String getCacheSize(File file) throws Exception {
        return getFormatSize(getFolderSize(file));
    }
}
